package com.joysuch.wwyt.mh.task;

import com.google.common.collect.Lists;
import com.joysuch.wwyt.common.constant.Constant;
import com.opencsv.CSVWriter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.influxdb.dto.QueryResult;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.Phaser;

@Slf4j
public class WriteCsvTaskForList implements Runnable {

    private final String filePath;
    private final List<QueryResult.Result> results;
    private final Phaser phaser;


    public WriteCsvTaskForList(String filePath, List<QueryResult.Result> results, Phaser phaser) {
        this.filePath = filePath;
        this.results = results;
        this.phaser = phaser;
    }

    @Override
    public void run() {
        CSVWriter writer = null;
        try {
            List<String[]> data = builderResultArr(results);
            String csvName = StringUtils.join(FilenameUtils.getFullPath(filePath), FilenameUtils.getBaseName(filePath), Constant.CSV);
            // 创建文件所在目录
            File file = new File(FilenameUtils.getFullPath(csvName));
            if (!file.exists()) {
                file.mkdirs();
            }
            char escape = CSVWriter.DEFAULT_ESCAPE_CHARACTER;
            char separate = CSVWriter.DEFAULT_SEPARATOR;
            char quote = CSVWriter.DEFAULT_QUOTE_CHARACTER;
            String lineEnd = CSVWriter.DEFAULT_LINE_END;
            writer = new CSVWriter(new OutputStreamWriter(new FileOutputStream(csvName), StandardCharsets.UTF_8), separate, quote, escape, lineEnd);
            writer.writeAll(data);
            writer.flush();
        } catch (Exception e) {
            log.error("将数据写入CSV出错:", e);
        } finally {
            phaser.arriveAndDeregister();
            if (null != writer) {
                try {
                    writer.close();
                } catch (IOException e) {
                    log.error("关闭文件输出流出错:", e);
                }
            }
        }
    }

    private List<String[]> builderResultArr(List<QueryResult.Result> results) {
        List<String[]> data = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(results)) {
            for (QueryResult.Result r : results) {
                List<QueryResult.Series> series = r.getSeries();
                if (!CollectionUtils.isEmpty(series)) {
                    for (QueryResult.Series ser : series) {
                        final List<String> columns = ser.getColumns();
                        if (!CollectionUtils.isEmpty(columns)) {
                            data.add(columns.toArray(new String[columns.size()]));
                            List<List<Object>> records = ser.getValues();
                            if (!CollectionUtils.isEmpty(records)) {
                                for (List<Object> record : records) {
                                    if (!CollectionUtils.isEmpty(record)) {
                                        String[] array = new String[record.size()];
                                        for (int i = 0; i < record.size(); i++) {
                                            array[i] = String.valueOf(record.get(i));
                                        }
                                        data.add(array);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return data;
    }
}
